"use strict";
/**
 * @name task
 * 任务成就
 */
const mvc = require('cosjs.mvc');
const random = mvc.library.require('random');

/**
 * @name rows
 * 普通任务记录
 */
exports.rows = function () {
    let taskModel = this.model.mongo('task', this.sid, this.uid);
    return taskModel.mget();
}

/**
 * @name submit
 * @param string id 任务ID
 * 普通任务领奖
 */
exports.submit = async function () {

    const arg = this.get('id', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    // await this.updater.data();
    for (let id of idList) {
        let taskConfig = this.config("task", id);
        if (!taskConfig) {
            return this.quick_error("M2PTA2", "任务配置不存在", id);
        }
        let taskModel = this.model.mongo('task', this.sid, this.uid);
        await taskModel.get(id).then(taskData => {
            if (taskData) {
                //限时任务判断
                if (taskConfig['ttl'] > 0 && taskData['ttl'] < this.library("time/today")) {
                    return this.quick_error("M2PTA3", "任务超时了", taskConfig['ttl']);
                }
                if (id <= taskData.val) {
                    return this.quick_error("M2PTA4", "该任务已经领取");
                }
                // this.updater.record.add(39,1);
                //任务链判断
                // console.log("taskConfig['series']:",taskConfig['series']);
                // console.log("taskConfig['limit'][0]:",typeof taskConfig['limit'][0]);
                // console.log("taskData['val'] :",typeof taskData['val']);
                // console.log("res:",taskConfig['series'] && taskConfig['limit'][0] && taskData['val'] != taskConfig['limit'][0]);
                if (taskConfig['series'] && taskConfig['limit'][0] && taskData['val'] != taskConfig['limit'][0]) {
                    return this.quick_error("M2PTA5", "前置任务没有完成", taskConfig['limit'][0]);
                }
            }
            return this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key']);
        }).then(val => {
            if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
                return this.quick_error("M2PTA6", '任务条件不达标', val, taskConfig['val'], taskConfig['compare']);
            }
            //任务道具
            this.updater.add(taskConfig['box'], taskConfig['count']);
            //更新任务记录
            let data = { "val": id };
            if (taskConfig['ttl'] > 0) {
                let stime = taskConfig['ttl'] == 7 ? this.library("time/week") : this.library("time/today");
                data['ttl'] = this.library("time/expire", stime, taskConfig['ttl']);
            }
            //累计完成的成长任务
            if (taskConfig['type'] === 6) {
                this.updater.record.add(47, 1);
            }
            if (taskConfig['type'] === 8 || taskConfig['type'] === 10 || taskConfig['type'] === 12 || taskConfig['type'] === 14 || taskConfig['type'] === 16 || taskConfig['type'] === 18) {
                //切割开头的2个数字，和47拼接，判断是否需要存
                let taskID = taskConfig['id'].toString();
                let recordID = 48 + taskID.substr(0, 2);
                let recordConfig = this.config("record", recordID);
                if (recordConfig) {
                    this.updater.record.add(recordID, 1);
                }
            }
            // if (taskConfig['type'] === 22) {
            //     this.updater.record.add(67, 1);
            // }
            if (taskConfig['type'] === 7 || taskConfig['type'] === 9 || taskConfig['type'] === 11 || taskConfig['type'] === 13 || taskConfig['type'] === 15 || taskConfig['type'] === 17) {
                // this.updater.record.add(taskConfig['type'],1);
                //切割结尾的2个数字，和47拼接，判断是否需要存
                let taskID = taskConfig['id'].toString();
                let recordID = 46 + taskID.substr(taskID.length - 2, 2);
                let recordConfig = this.config("record", recordID);
                if (recordConfig) {
                    this.updater.record.add(recordID, 1);
                }
            }
            switch (parseInt(id)) {
                case 200110:
                case 200111:
                case 200112:
                    this.updater.record.add(6701, 1);
                    break;
                case 200120:
                case 200121:
                case 200122:
                    this.updater.record.add(6702, 1);
                    break;
                case 200130:
                case 200131:
                case 200132:
                    this.updater.record.add(6703, 1);
                    break;
                case 200113:
                case 200123:
                case 200133:
                    this.updater.record.add(67, 1);
                    break;
                default:
            }
            //不知道当初写下面这条干啥
            // this.updater.record.add(parseInt(taskConfig['id']/10000)+"",1);
            // this.updater.record.add("testRecord",1);
            return taskModel.set(id, data).then(() => data);
        })
        // .then((data) => {
        //     return this.updater.save().then(() => data);
        // })
    }
    await this.updater.save();
    return arg;

}



/**
 * @name getDailyTask
 * 获取每日任务
 */
exports.getDailyTask = async function () {
    this.updater.daily.key("todayTask");
    await this.updater.data();
    let _task = this.updater.daily.get("todayTask") || [];
    // let _task = [];
    if (_task.length == 0) {
        //创建今日任务
        const taskConfig = this.config("taskDaily");
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        let localRate = [];
        for (let v in taskConfig) {
            if (taskConfig[v].type != 2) {
                localRate.push({ "id": taskConfig[v].id, "rate": taskConfig[v].rate });
            }
        }
        for (let i = 0; i < 5; i++) {
            let k = random.Relative(localRate, 'rate');
            if (k === false) {
                return this.quick_error("M2HS4", "卡池配置不匹配",);
            }
            _task.push({ "id": localRate[k].id, "flag": 0, "process": 0 });
            localRate.splice(k, 1);
        }
        this.updater.daily.set("todayTask", _task);
        await this.updater.save();
        return _task;
    } else {
        return _task;
    }
}



/**
 * @name rollDailyTask
 * @param int index 任务下标
 * 更换每日任务
 */
exports.rollDailyTask = async function () {
    let index = this.get('index', 'int');
    if (!index) {
        return this.error('args empty');
    }
    index = index - 1;
    this.updater.daily.key("todayTask");
    this.updater.daily.key("rollDailyTask");

    await this.updater.data();
    let _task = this.updater.daily.get("todayTask") || [];
    let rollTime = this.updater.daily.get("rollDailyTask") || 0;
    if (_task.length == 0) {
        return this.error('bad request');
    } else {
        if (index > _task.length) {
            return this.quick_error('M2saghge140', '不存在该任务');
        }
        let oldID = _task[index].id;
        if (_task[index].flag == 1) {
            return this.quick_error('M2saghge140', '任务已完成');
        }
        const taskConfig = this.config("taskDaily");
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        let localRate = [];
        for (let v in taskConfig) {
            if (taskConfig[v].type != 2) {
                let flag = 1;
                for (let task in _task) {
                    if (_task[task].id == taskConfig[v].id) {
                        flag = 0;
                    }
                }
                if (flag) {
                    localRate.push({ "id": taskConfig[v].id, "key": taskConfig[v].key, "rate": taskConfig[v].rate });
                }
            }
        }
        let k = random.Relative(localRate, 'rate');
        if (k === false) {
            return this.quick_error("M2HS4", "卡池配置不匹配",);
        }
        this.updater.daily.key(localRate[k].key);
        await this.updater.data();
        let process = this.updater.daily.get(localRate[k].key) || 0;
        _task[index] = ({ "id": localRate[k].id, "flag": 0, "process": process });
        // let i = 0;
        // for(let id in taskConfig){
        //     i++;
        //   }

        // while(true){
        //     var cutFlag = 0;
        //     for(let id in taskConfig){
        //         if(id != oldID){
        //             let randNum = Math.roll(1, i);
        //             if(randNum < parseInt(i-(i/2))){
        //                 var flag = 0;
        //                 for(let k of _task){
        //                     if(k.id == id){
        //                         flag = 1;
        //                         break;
        //                     }
        //                 }
        //                 if(!flag){
        //                     _task[index] = ({"id":id,"flag":0,"process":0});
        //                     i++;
        //                     this.updater.daily.add("rollDailyTask",1);
        //                     cutFlag = 1;
        //                     break;
        //                 }
        //             }
        //         }
        //       }
        //       if(cutFlag){
        //         break;
        //       }
        // }
        this.updater.daily.set("todayTask", _task);
        await this.updater.save();
        return _task;
    }
}


/**
 * @name daily
 * @param string idList 任务下标串,以","分割
 * 日任务领奖
 */
exports.daily = async function () {
    const arg = this.get('idList', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    this.updater.daily.key("todayTask");
    await this.updater.data();
    let _task = this.updater.daily.get("todayTask") || [];
    for (let i of idList) {
        if (parseInt(i) > _task.length) {
            continue;
        }
        let id = _task[parseInt(i)].id;
        let taskConfig = this.config("taskDaily", id);
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        await this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key'].toString()).then(val => {
            if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
                return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig['val'], taskConfig['compare']);
            }
            this.updater.add(taskConfig['box'], taskConfig['count']);
            if (taskConfig["active"] > 0) {
                this.updater.daily.add("active", taskConfig["active"]);
            }
            if (_task.indexOf(id) >= 0) {
                return this.quick_error("M2PTA53", "已经领取过了");
            }
            if (_task[parseInt(i)].flag == 0) {
                _task[parseInt(i)].flag = 1;
            }
            //累计每日任务完成数量
            if (taskConfig['dtype'] === 0) {
                // this.updater.record.add("activeRequire",taskConfig['active']);
                this.updater.daily.add("record." + "10", taskConfig['active']);
            }

        });
    }
    this.updater.daily.set("todayTask", _task);
    return this.updater.save();
}


/**
 * @name dailyProcess
 * @param int id 任务ID
 * 日任务进度领奖
 */
exports.dailyProcess = async function () {
    const id = this.get('id', 'int');
    if (!id) {
        return this.quick_error('M2saghge140', '参数错误');
    }
    // const id = this.get('id', 'string');
    // if (!id) {
    //     return this.quick_error('M2saghge140', '参数错误');
    // }
    this.updater.daily.key("todayTask");
    this.updater.daily.key("dailyProcess");
    await this.updater.data();
    let dailyProcess = this.updater.daily.get("dailyProcess") || [];
    // let todayTask = this.updater.daily.get("todayTask") || [];
    for (let i in dailyProcess) {
        if (dailyProcess[i] == id) {
            return this.quick_error("M2PTA51", "任务已经领取过了");
        }
    }
    let taskConfig = this.config("taskDaily", id);
    if (!taskConfig) {
        return this.quick_error("M2PTA51", "配置不存在");
    }
    await this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key'].toString()).then(val => {
        if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
            return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig['val'], taskConfig['compare']);
        }
        this.updater.add(taskConfig['box'], taskConfig['count']);
        if (taskConfig["active"] > 0) {
            this.updater.daily.add("active", taskConfig["active"]);
        }
        // if (_task.indexOf(id) >= 0) {
        //     return this.quick_error("M2PTA53", "已经领取过了");
        // }
        // if(_task[parseInt(i)].flag == 0){
        //     _task[parseInt(i)].flag = 1;
        // }
        //累计每日任务完成数量
        if (taskConfig['dtype'] === 0) {
            // this.updater.record.add("activeRequire",taskConfig['active']);
            this.updater.daily.add("record." + "10", taskConfig['active']);
        }
    });
    dailyProcess.push(id);
    this.updater.daily.set("dailyProcess", dailyProcess);
    return this.updater.save();
}

/**
 * @name week
 * @param string idList 任务下标串,以","分割
 * 周任务领奖
 */
exports.week = async function () {
    // let id = this.get("id", "int") || 0;
    // if (!id) {
    //     return this.quick_error("M2PTA50", "参数为空");
    // }
    // let taskConfig = this.config("taskWeek", id);
    // if (!taskConfig) {
    //     return this.quick_error("M2PTA51", "配置不存在");
    // }
    const arg = this.get('idList', 'string').trim();
    if (!arg) {
        return this.quick_error('M2saghge140', '必须有消耗品');
    }
    let idList = arg.split(",");
    let idMap = new Map();
    for (let id of idList) {
        if (idMap.has(id)) {
            return this.quick_error('M2saghge140', 'ID重复,领取失败');
        }
        idMap.set(id, 1);
    }
    //taskWeek
    this.updater.role.key("taskWeek");
    await this.updater.data();
    let _taskWeek = this.updater.role.get("taskWeek") || { 'id': 0, 'task': [] };
    let _weekCuo = this.library("time/week");
    if (_weekCuo != _taskWeek.id) {
        _taskWeek.id = _weekCuo;
        _taskWeek.task = [];
    }
    // let _task = _taskWeek.task;
    for (let id of idList) {
        // if(parseInt(i) > _taskWeek.task.length){
        //     continue;
        // }
        // let id = _taskWeek.task[parseInt(i)].id;
        let taskConfig = this.config("taskWeek", id);
        if (!taskConfig) {
            return this.quick_error("M2PTA51", "配置不存在");
        }
        await this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key'])
            .then(val => {
                if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
                    return this.quick_error("M2PTA111", 'task_val_limit', val, taskConfig['val'], taskConfig['compare']);
                }
                this.updater.add(taskConfig['box'], taskConfig['count']);
                if (taskConfig["active"] > 0) {
                    this.updater.daily.add("active", taskConfig["active"]);
                }

                if (_taskWeek.task.indexOf(id) >= 0) {
                    return this.quick_error("M2PTA53", "已经领取过了");
                }
                _taskWeek.task.push(id);
                this.updater.role.set("taskWeek", _taskWeek);
                // if(taskConfig.dtype===0){
                //     //普通任务
                //     //成交 活跃度任务完成数量
                //     this.updater.record.add(93136,1);
                //     this.updater.daily.add('dtaskN',1);
                // }
                //累计每日任务完成数量
                if (taskConfig['dtype'] === 0) {
                    // this.updater.record.add("activeRequire",taskConfig['active']);
                    this.updater.daily.add("record." + "57", taskConfig['active']);
                }
                // return this.updater.save();

                // return this.updater.data().then(() => {

                // });
            })

    }
    return this.updater.save();
}


/**
 * @name cheackEggTask
 * 通知服务器去检验抓蛋限时任务
 */
exports.cheackEggTask = async function () {
    let now = this.updater.time;
    let dailyCache = this.model.redis("dailyCache", this.sid);
    let dailyCacheData = await dailyCache.get(this.uid);
    if (dailyCacheData == null) {
        return this.quick_error("m2sgrbs1", "没有前置的cache信息");
    }
    let data = JSON.parse(dailyCacheData[0]);
    await dailyCache.del(this.uid);
    let item = this.model.mongo('item', this.sid, this.uid);
    let option = {
        "multi": true,
        "projection": ["id", "val", "condition", "endTime"]
    };
    let taskRet = await item.find({
        'uid': this.uid,
        'bag': 90,
    }, option);
    //    console.log()
    for (let k in taskRet) {
        if (taskRet[k].endTime <= now) {
            //过期
            this.updater.item.del(taskRet[k]._id);
        } else {
            //未过期    
            //在本次完成
            if (taskRet[k].condition == data.k) {
                let taskConfig = this.config("eggTask", taskRet[k].id);
                if (!taskConfig) {
                    return this.quick_error("M2PTA51", "配置不存在");
                }
                if ((taskRet[k].val + data.v) >= taskConfig["times"]) {
                    //本次达成条件，新增7天保存时间
                    taskRet[k].val += data.v;
                    taskRet[k].endTime += 7 * 24 * 3600 * 1000;
                    this.updater.item.set(taskRet[k]._id, taskRet[k]);
                } else {
                    this.updater.item.set(taskRet[k]._id, "val", data.v + taskRet[k].val);
                }
            }
        }
    }
    return this.updater.save()
}


/**
 * @name deleteEggTask
 * @param string id 任务唯一ID
 * 放弃抓蛋限时任务
 */
exports.deleteEggTask = async function () {
    let id = this.get("id", "string") || "";
    if (!id) {
        return this.quick_error("M2PTA50", "参数为空");
    }
    this.updater.daily.key('eggTaskDelete');
    this.updater.item.key(id);
    await this.updater.data();
    let task = this.updater.item.get(id);
    if (!task) {
        return this.quick_error("M2saghge20", " 任务不存在", id);
    }
    let num = this.updater.daily.get('eggTaskDelete') || 0;
    const maxFreeTime = this.config('base', 'eggTaskDeleteFree').val;

    if (num >= maxFreeTime) {
        const subCost = this.config('base', 'eggTaskDeleteCost').strVal.split(':');
        this.updater.sub(parseInt(subCost[0]), parseInt(subCost[1]));
    }
    this.updater.daily.add('eggTaskDelete', 1);
    //eggTaskDeleteFree 消耗
    await this.updater.item.del(id);
    return this.updater.save();
}





/**
 * @name eggTask
 * @param string id 任务唯一ID
 * 限时抓蛋任务领奖
 */
exports.eggTask = async function () {
    let id = this.get("id", "string") || "";
    if (!id) {
        return this.quick_error("M2PTA50", "参数为空");
    }

    this.updater.item.key(id);
    this.updater.daily.key('eggTaskNum');
    this.updater.daily.key('eggTaskComplete');
    await this.updater.data();
    let eggTaskComplete = this.updater.daily.get('eggTaskComplete') || [];
    let eggTaskNum = this.updater.daily.get('eggTaskNum') || 0;
    if (eggTaskNum < this.config('base', 'eggTaskExtraGift').val) {
        //需要给额外奖励
        let addList = this.config('base', 'eggTaskExtraGift').strVal.split(',');
        for (let i = 0; i < addList.length; i++) {
            let arr = addList[i].split(':');
            this.updater.add(parseInt(arr[0], 10), parseInt(arr[1], 10));
        }
    }

    let taskData = this.updater.item.get(id);
    if (!taskData) {
        return this.quick_error('M2saghge190', '消耗的装备不存在', id);
    }
    let taskConfig = this.config("eggTask", taskData.id);
    if (!taskConfig) {
        return this.quick_error("M2PTA51", "配置不存在");
    }
    if (taskData.val < taskConfig["times"]) {
        return this.quick_error("M2PTA51", "条件不允许");
    }
    //给奖励
    this.updater.add(taskConfig['boxID'], 1);
    eggTaskComplete.push(taskData.id);
    this.updater.item.del(id);
    // this.updater.daily.add('eggTaskNum', 1);
    this.updater.daily.add("record." + "39", 1);
    this.updater.record.add(39, 1);
    this.updater.daily.set("eggTaskComplete", eggTaskComplete);
    return this.updater.save()

    // let taskModel = this.model.mongo('eggTask', this.sid, this.uid);
    // return taskModel.get(id).then(taskData => {
    //     if (taskData) {
    //         //读表判断是否可以领取
    //         if(taskData.val < taskConfig["times"]){
    //             return this.quick_error("M2PTA51", "条件不允许");
    //         }
    //         //给奖励
    //         this.updater.add(taskConfig['boxID'],1);
    //         return this.updater.eggTask.del(id);
    //     }else{
    //         return this.quick_error("M2PTA4", "没找到对应任务");
    //     }
    // }).then(() => {
    //     return this.updater.save().then();
    // })



    // const arg = this.get('idList', 'string').trim();
    // if (!arg) {
    //     return this.quick_error('M2saghge140', '必须有消耗品');
    // }
    // let idList = arg.split(",");
    // let idMap = new Map();
    // for(let id of idList){
    //     if(idMap.has(id)){
    //         return this.quick_error('M2saghge140', 'ID重复,领取失败');
    //     }
    //     idMap.set(id,1);
    // }

    // let taskModel = this.model.mongo('eggTask', this.sid, this.uid);
    // //



    return taskModel.get(id).then(taskData => {
        if (taskData) {
            //限时任务判断
            if (taskConfig['ttl'] > 0 && taskData['ttl'] < this.library("time/today")) {
                return this.quick_error("M2PTA3", "任务超时了", taskConfig['ttl']);
            }

            if (id <= taskData.val) {
                return this.quick_error("M2PTA4", "该任务已经领取");
            }

            //任务链判断
            if (taskConfig['series'] && taskConfig['limit'][0] && taskData['val'] !== taskConfig['limit'][0]) {
                return this.quick_error("M2PTA5", "前置任务没有完成", taskConfig['limit'][0]);
            }
        }
        return this.library.call(this.updater, "valuesNew", taskConfig['tar'], taskConfig['key']);
    }).then(val => {
        if ((taskConfig['compare'] > 0 && val > taskConfig['val']) || (taskConfig['compare'] <= 0 && val < taskConfig['val'])) {
            return this.quick_error("M2PTA6", '任务条件不达标', val, taskConfig['val'], taskConfig['compare']);
        }
        //任务道具
        this.updater.add(taskConfig['box'], taskConfig['count']);
        // for (let d of taskConfig['item']) {
        //     if (d.id && d.num) {
        //         this.updater.add(d.id, d.num);
        //     }
        // }
        //更新任务记录
        let data = { "val": id };
        if (taskConfig['ttl'] > 0) {
            let stime = taskConfig['ttl'] == 7 ? this.library("time/week") : this.library("time/today");
            data['ttl'] = this.library("time/expire", stime, taskConfig['ttl']);
        }
        //累计完成的成长任务
        if (taskConfig['dtype'] === 4) {
            this.updater.record.add("activeRequire", taskConfig['active']);
        }
        return taskModel.set(id, data).then(() => data);
    }).then((data) => {
        return this.updater.save().then(() => data);
    })
}